package gui;

import dados.BancoQuestoes;
import dados.PastaCorrecao;
import dados.Questao;
import gui.modelos.KeyListenerJanela;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import dados.Preferencias;
import dados.QuestaoProva;
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.UIManager;

import logica.Constantes;
import logica.GerenciaBanco;
import logica.GerenciaSerializacao;
import logica.Utilitarios;
/**
 *
 * @author  Yuri Maia
 */
public class Bancos extends javax.swing.JDialog {
    
    private ArrayList<QuestaoProva> bancoQuestoes = null;
    private ArrayList<QuestaoProva> estadoInicial = null;
    /** Creates new form Entradas */
    public Bancos(Principal pai) {
        super(pai, "Banco de Questões", true);
        initComponents();
        bancoQuestoes = new ArrayList();
        estadoInicial = new ArrayList();
        estadoInicial.addAll(bancoQuestoes);
        Janelas.alinharContainer(this);
        txtEnunciado.setEditable(false);

        this.addKeyListener(new KeyListenerJanela());
    }
    
    public Bancos(Principal pai, ArrayList<QuestaoProva> provas) {
        super(pai, "Banco de Questões", true);
        initComponents();
        bancoQuestoes = provas;
        estadoInicial = new ArrayList();
        estadoInicial.addAll(bancoQuestoes);
        txtEnunciado.setEditable(false);
        iniciarListas();
        Janelas.alinharContainer(this);
        this.addKeyListener(new KeyListenerJanela());
    }
    
    private void iniciarListas() {
        if (!bancoQuestoes.isEmpty()) {
            GerenciaBanco ger = new GerenciaBanco(bancoQuestoes);

            listaQuestoes.setListData(ger.getVetorQuestoes());
            listaQuestoes.setSelectedIndex(0);
            listaVersoes.setListData(ger.getVetorVersoes(0));
            
            if (listaVersoes.getModel().getSize() > 0) { 
                listaVersoes.setSelectedIndex(0);

                txtEnunciado.setText(bancoQuestoes.get(0).getQuestao(0).getEnunciado());
            }
        }
  }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        grupoCheckbox = new javax.swing.ButtonGroup();
        btnSalvar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listaVersoes = new javax.swing.JList();
        btnImportar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        listaQuestoes = new javax.swing.JList();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane5 = new javax.swing.JScrollPane();
        txtEnunciado = new javax.swing.JTextArea();
        btnCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Entradas e Gabaritos");

        btnSalvar.setText("Salvar Alterações");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Lista (Entradas / Gabaritos)"));

        listaVersoes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listaVersoesMouseClicked(evt);
            }
        });
        listaVersoes.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listaVersoesValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(listaVersoes);

        btnImportar.setText("Importar banco");
        btnImportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportarActionPerformed(evt);
            }
        });

        jLabel2.setText("Questões");

        listaQuestoes.setModel(new javax.swing.AbstractListModel() {
            String[] strings = {" " };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        listaQuestoes.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listaQuestoesValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(listaQuestoes);

        jLabel4.setText("Versões");

        jLabel6.setText("Enunciado");

        txtEnunciado.setColumns(20);
        txtEnunciado.setRows(5);
        jScrollPane5.setViewportView(txtEnunciado);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel6)
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jPanel1Layout.createSequentialGroup()
                                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE)
                                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED))
                                    .add(jPanel1Layout.createSequentialGroup()
                                        .add(jLabel2)
                                        .add(49, 49, 49)))
                                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(jLabel4)
                                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE))))
                        .add(46, 46, 46)
                        .add(btnImportar)
                        .add(10, 10, 10))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jScrollPane5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 345, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(btnImportar)
                .add(29, 29, 29)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(jLabel4))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jScrollPane1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 10, Short.MAX_VALUE)
                .add(jLabel6)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 138, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18))
        );

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(btnCancelar)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 185, Short.MAX_VALUE)
                        .add(btnSalvar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnCancelar)
                    .add(btnSalvar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        
        try {
/*salvar apenas as questoes*/            
            int i = 0;
            int nroQuestoes = bancoQuestoes.size();
            int[] notasQuestoes = Utilitarios.calcularNotas(nroQuestoes);
            for(QuestaoProva questao : bancoQuestoes){
                ArrayList<Questao> versoes = questao.getArrayListQuestao();
                for(Questao versao : versoes){
                    int nroTestes = versao.getTestes().size();
                    if (nroTestes == 0) {
                        throw new IOException();
                    }
                    int[] notasTestes = Utilitarios.calcularNotas(nroTestes);
                    versao.setNotaMax(notasQuestoes[i]);
                    if (notasTestes != null) {
                        for (int j = 0; j <= nroTestes - 1; j++) {
                            versao.getTeste(j).setPorcentagemNotaMax(notasTestes[j]);
                        }
                    }
                }
            i++;
            }
            /* Faz o c�lculo das notas padr�es m�ximas das quest�es e dos testes. */
            for(QuestaoProva questao: bancoQuestoes)
                if(questao.getArrayListQuestao().isEmpty())
                    throw new IOException();
            
            BancoQuestoes.setInstancia(bancoQuestoes);
            
            if(PastaCorrecao.getInstancia() != null){
            	GerenciaSerializacao ser = new GerenciaSerializacao();
            	ser.serializar();        
            	JOptionPane.showMessageDialog(null, "Alterações salvas com sucesso!", "Sucesso!", JOptionPane.INFORMATION_MESSAGE);
            }
            this.dispose();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "Existe uma questão que não tem " +
                    "nenhum teste associado!\n Por favor adicione no mínimo um teste!", 
                    "Questão sem teste!", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnSalvarActionPerformed
    
    private void btnImportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImportarActionPerformed
        UIManager.put("FileChooser.openDialogTitleText", "Importar Banco de Questões...");
        File arquivo = null;
        
        File dirPadrao = Preferencias.getInstancia().getDiretorioNavegacao();
        JFileChooser fc = new JFileChooser();
        if (dirPadrao != null) {
            fc.setCurrentDirectory(dirPadrao);
        }
        
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int resultado = fc.showOpenDialog(this);
        Janelas.alinharContainer(fc);
        if (resultado == JFileChooser.CANCEL_OPTION) {
            return;
        } else {
            arquivo = fc.getSelectedFile();
            try {
                GerenciaSerializacao gerSer = new GerenciaSerializacao();
                gerSer.desserializarBancoQuestoes(arquivo);
                bancoQuestoes = (ArrayList<QuestaoProva>)BancoQuestoes.getInstancia().getArrayListQuestaoProva().clone();
                iniciarListas();
                JOptionPane.showMessageDialog(this, "Importação Concluída!", "Concluído!",
                    JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "O arquivo informado não constitui " +
                        "um arquivo válido de questões para o Corretor!", "Arquivo Inválido!",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
}//GEN-LAST:event_btnImportarActionPerformed

    private void listaVersoesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listaVersoesMouseClicked
//        if (evt.getClickCount() > 1) {
//            int testeSelecionado = listaVersoes.getSelectedIndex();
//            Questao questao = questoes.get(listaProvas.getSelectedIndex());
//            TabelasTeste tab = new TabelasTeste(null, testeSelecionado, questao.getTeste(testeSelecionado));
//            tab.setVisible(true);
//            if (tab.getSaidaNormal()) {
//                questao.editarTeste(testeSelecionado, tab.getTeste());
//            }
//        }
}//GEN-LAST:event_listaVersoesMouseClicked

    private void listaQuestoesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listaQuestoesValueChanged
        int nroVersoes;
        
        if (listaQuestoes.getSelectedIndex() >= 0) {
            GerenciaBanco ger = new GerenciaBanco(bancoQuestoes);
           
            
            listaVersoes.setListData(new String[0]);
            txtEnunciado.setText("");
            nroVersoes = bancoQuestoes.get(listaQuestoes.getSelectedIndex())
                    .getArrayListQuestao().size();
            if(nroVersoes > 0) {
                listaVersoes.setListData(ger.getVetorVersoes(
                        listaQuestoes.getSelectedIndex()));
                listaVersoes.setSelectedIndex(0);
                txtEnunciado.setText(bancoQuestoes
                    .get(listaQuestoes.getSelectedIndex()) 
                    .getQuestao(listaVersoes.getSelectedIndex())
                    .getEnunciado());
            }
        }
    }//GEN-LAST:event_listaQuestoesValueChanged

    private void listaVersoesValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listaVersoesValueChanged
        if (listaVersoes.getSelectedIndex() >= 0) {
            txtEnunciado.setText(bancoQuestoes
                .get(listaQuestoes.getSelectedIndex()) 
                .get(listaVersoes.getSelectedIndex())
                .getEnunciado());
        }
    }//GEN-LAST:event_listaVersoesValueChanged
    
    public static void salvar(){
    	GerenciaSerializacao ser = new GerenciaSerializacao();
    	ser.serializar();
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnImportar;
    private javax.swing.JButton btnSalvar;
    private javax.swing.ButtonGroup grupoCheckbox;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JList listaQuestoes;
    private javax.swing.JList listaVersoes;
    private javax.swing.JTextArea txtEnunciado;
    // End of variables declaration//GEN-END:variables
    
}
